package top.broncho.mvvm.ui.widget

import android.animation.ValueAnimator
import android.view.View
import androidx.coordinatorlayout.widget.CoordinatorLayout


const val MODE_TITLE = 233
const val MODE_BOTTOM = 2333

class TranslateAnimateHelper(
    var target: View, var mode: Int = MODE_BOTTOM, override var state: Int = STATE_SHOW
) : AnimateHelper {

    private val firstY by lazy {
        target.y
    }
    private val margin by lazy {
        val layoutParams = target.layoutParams as CoordinatorLayout.LayoutParams
        layoutParams.topMargin; +layoutParams.bottomMargin
    }

    override fun show() {
        if (mode == MODE_TITLE) {
            showTitle()
        } else if (mode == MODE_BOTTOM) {
            showBottom()
        }
    }

    private fun hideTitle() {
        val va =
            ValueAnimator.ofFloat(target.y, -target.height.toFloat()).apply {
                duration = 300
                addUpdateListener {
                    target.y = (it.animatedValue as Float)
                }
            }
        va.start()
        state = STATE_HIDE
    }

    private fun showTitle() {
        val va = ValueAnimator.ofFloat(target.y, 0f).apply {
            duration = 300
            addUpdateListener {
                target.y = (it.animatedValue as Float)
            }
        }
        va.start()
        state = STATE_SHOW
    }

    override fun hide() {
        if (mode == MODE_TITLE) {
            hideTitle()
        } else if (mode == MODE_BOTTOM) {
            hideBottom()
        }
    }

    private fun showBottom() {
        val va = ValueAnimator.ofFloat(target.y, firstY).apply {
            duration = 300
            addUpdateListener {
                target.y = (it.animatedValue as Float)
            }
        }
        va.start()
        state = STATE_SHOW
    }

    private fun hideBottom() {
        val va =
            ValueAnimator.ofFloat(target.y, firstY + target.height + margin).apply {
                duration = 300
                addUpdateListener {
                    target.y = (it.animatedValue as Float)
                }
            }
        va.start()
        state = STATE_HIDE
    }

}